import React, { useEffect, useRef, useState } from "react";
import * as echarts from "echarts";

interface LineContentProps {
  record: any;
}

const baseOptions = {
  itemStyle: {
    borderRadius: 10,
  },
  grid: {
    left: "40",
    right: "30",
    bottom: "30",
    top: "30",
  },
};

const showStep = 4;
const LineContent: React.FC<LineContentProps> = ({ record }) => {
  const echartsRef = useRef<HTMLDivElement | null>(null);
  const myChartRef = useRef<echarts.EChartsType | null>(null);
  const referenceDivRef = useRef<HTMLDivElement>(null);

  const generateTimePoints = (
    startTime: Date,
    endTime: Date,
    pointsCount: number
  ): Date[] => {
    if (pointsCount < 2) {
      throw new Error("pointsCount至少需要2个");
    }
    const start = startTime.getTime();
    const end = endTime.getTime();
    const interval = (end - start) / (pointsCount - 1);
    return Array.from({ length: pointsCount }).map(
      (_, i) => new Date(start + interval * i)
    );
  };
  const formatTimestamp = (timestamp: any) => {
    const date = new Date(timestamp);

    const hours = date.getHours();
    const formattedHours = hours < 10 ? "0" + hours : hours;
    const minutes = date.getMinutes();
    const formattedMinutes = minutes < 10 ? "0" + minutes : minutes;

    const month = date.getMonth() + 1;
    const day = date.getDate();

    return `${formattedHours}:${formattedMinutes}\n${month}/${day}`;
  };

  const setCharts = (record: any) => {
    if (myChartRef.current) {
      myChartRef.current.clear();
      myChartRef.current.resize();
    } else {
      myChartRef.current = echarts.init(echartsRef.current);
    }
    const resOptions: any = {
      ...baseOptions,
      tooltip: {
        trigger: "axis",
        textStyle: { color: "#fff" },
        backgroundColor: "rgba(50,50,50,0.7)",
      },
    };
    if (
      record &&
      record.pastValue &&
      record.pastValue.length > 0 &&
      record.time &&
      record.time.length > 0
    ) {
      const labelX: any[] = [];
      const now = new Date();
      const past = record.time[0];
      const startTime = new Date(now.getTime() - past * 60 * 60 * 1000);
      const pointsCount = record.pastValue.length;
      const points = generateTimePoints(startTime, now, pointsCount);
      const history = points.map((x, i) => [x, record.pastValue[i]]);
      const mid = Math.floor(history.length / 2);
      labelX.push({
        x: history[mid][0].getTime(),
        label: `${past}h`,
      });
      let currentTime = now;
      const newTimes: any[] = [];
      record.time.slice(1).forEach((hours: any, i: number) => {
        currentTime = new Date(currentTime.getTime() + hours * 60 * 60 * 1000);
        if (i < showStep) {
          newTimes.push(currentTime);
        }
      });
      const future: any[] = [];
      newTimes.forEach((x, i) => {
        if (i < showStep) {
          future.push([x, record.value[i + 1]]);
        }
      });

      const endTime = new Date(newTimes[newTimes.length - 1].getTime());
      // const allValue = [...record.pastValue, ...record.value];
      // let yMin = Math.floor(Math.min(...allValue) / 100) * 100 - 50;
      const yMin = 780;
      // const yMax = 860;
      const yAxisArr: any[] = [
        {
          type: "value",
          splitLine: {
            show: false,
          },
          axisLabel: {
            formatter: function (value: any) {
              return `${Math.round(value)}`; // 取整显示
            },
          },
          splitNumber: 4,
          min: yMin,
          // max: yMax,
        },
      ];
      // console.log(yMin);

      const markLine: any[] = [
        [
          { xAxis: now, yAxis: yMin },
          {
            name: `当前`,
            xAxis: now,
            yAxis: record.pastValue[record.pastValue.length - 1],
            label: {
              rotate: 45, // 旋转45度
            },
          },
        ],
      ];

      const markArea: any[] = [
        [
          {
            xAxis: now,
            label: {
              show: true,
              position: "insideBottomRight",
              align: "center",
              // verticalAlign: "bottom",
              verticalAlign: "top",
              distance: 0,
              offset: [0, 5],
              formatter: formatTimestamp(newTimes[0]),
              opacity: 0.6,
              fontSize: 9,
            },
          },
          { xAxis: newTimes[0] },
        ],
      ];
      const stepCount = Math.min(record.time.length, showStep + 1);
      for (var i = 1; i < stepCount; ++i) {
        markLine.push([
          {
            xAxis: newTimes[i - 1],
            yAxis: yMin,
            label: {
              show: true,
              position: "end",
              // formatter: steps[i - 1],
              formatter: `第${i}步`,
              rotate: 45, // 旋转45度

              // formatter: `${record.value[i]} ${record.unit || ""}`,
            },
          },
          {
            xAxis: newTimes[i - 1],
            yAxis: record.value[i],
          },
        ]);
        if (i < stepCount - 1) {
          markArea.push([
            {
              xAxis: newTimes[i - 1],
              label: {
                position: "insideBottomRight",
                align: "center",
                // verticalAlign: i % 2 === 0 ? "bottom" : "top",
                // distance: i % 2 === 0 ? 5 : -5,
                verticalAlign: "top",
                distance: 0,
                // offset: i % 2 === 0 ? [0, 0] : [0, 5],
                offset: [0, 5],
                // formatter: `${record.time[i + 1]}h`,
                formatter: formatTimestamp(newTimes[i]),
                opacity: 0.6,
                fontSize: 9,
              },
            },
            { xAxis: newTimes[i] },
          ]);
        }
      }

      const seriesArr: any[] = [
        {
          name: record.tagName,
          type: "line",
          tooltip: {
            valueFormatter: function (value: string) {
              return `${value} ${record.unit || ""}`;
            },
          },
          showSymbol: false,
          data: history,
          areaStyle: { color: "rgba(235,49,151,0.3)" },
          lineStyle: {
            color: "#EB3197",
          },
          itemStyle: {
            color: "#EB3197",
          },
          markArea: {
            silent: true,
            itemStyle: {
              color: "transparent",
            },
            label: {
              color: "#FFFFFF",
              opacity: 0.6,
            },
            data: [
              [
                {
                  xAxis: startTime,
                  label: {
                    show: true,
                    position: "insideBottomRight",
                    align: "center",
                    verticalAlign: "top",
                    distance: 0,
                    offset: [0, 5],
                    formatter: formatTimestamp(now),
                    fontSize: 9,
                    // rotate: 45
                    // formatter: `${record.time[0]}h`,
                  },
                },
                { xAxis: now },
              ],
            ],
          },
        },
        {
          name: record.tagName,
          type: "line",
          data: future,
          tooltip: {
            valueFormatter: function (value: string) {
              return `${value} ${record.unit || ""}`;
            },
          },
          lineStyle: {
            width: 0,
          },
          itemStyle: {
            color: "#15CCFF",
          },
          showNull: false,
          symbolSize: 0,
          showSymbol: true,
          emphasis: {
            focus: "series",
          },
          markLine: {
            symbol: ["none", "circle"],
            symbolSize: 8,
            label: {
              show: true,
              color: "#FFFFFF",
              fontWeight: "0.05rem",
            },
            lineStyle: {
              color: "#15CCFF",
              type: "dashed",
            },
            data: markLine,
          },
          markArea: {
            silent: true,
            itemStyle: {
              color: "transparent",
            },
            label: {
              color: "#FFFFFF",
            },
            data: markArea,
          },
        },
      ];

      const xAxisArr: any[] = [
        {
          type: "time",
          // name: "调整时间",
          // nameTextStyle: {
          //   padding: [0, 0, -17, 6], // 调整名称位置，使其更靠近右下角
          //   verticalAlign: "bottom", // 垂直对齐到底部
          //   align: "right", // 水平对齐到右侧
          // },
          min: startTime,
          max: endTime,
          axisLabel: {
            show: false,
            interval: 0,
            formatter: "",
          },
          axisTick: {
            show: false,
          },
        },
      ];

      const graphicArr = {
        elements: [
          {
            type: "text",
            left: 30,
            bottom: 8,
            style: {
              text: formatTimestamp(startTime),
              fill: "#FFF",
              opacity: 0.6,
              fontSize: 9,
            },
          },
        ],
      };

      resOptions.yAxis = yAxisArr;
      resOptions.series = seriesArr;
      resOptions.xAxis = xAxisArr;
      resOptions.graphic = graphicArr;
    }
    myChartRef.current.setOption(resOptions);
  };

  useEffect(() => {
    if (!referenceDivRef.current) return;
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width, height } = entry.contentRect;
        setDimensions({
          refHeight: height,
          refWidth: width,
        });
      }
    });
    resizeObserver.observe(referenceDivRef.current);
    return () => {
      resizeObserver.disconnect();
    };
  }, []);

  const [dimensions, setDimensions] = useState({
    refHeight: 0,
    refWidth: 0,
  });

  useEffect(() => {
    if (record) {
      setCharts(record);
    }
  }, [record, dimensions]);

  return (
    <div ref={referenceDivRef}>
      <div
        style={{
          margin: "auto",
          height: "8rem",
          marginBottom: "0.8rem",
        }}
        ref={echartsRef}
      ></div>
    </div>
  );
};

export default LineContent;
